import heapq


class AuthenticationManager:

    def __init__(self, timeToLive: int):
        self.ttl = timeToLive
        self.timeline = []
        self.tokens = {}

    def generate(self, token: str, current: int) -> None:
        self._remove(current)
        if token not in self.tokens:  # 题目保证独一无二
            self.tokens[token] = current + self.ttl
            heapq.heappush(self.timeline, (current + self.ttl, token))

    def renew(self, token: str, current: int) -> None:
        self._remove(current)
        if token in self.tokens:
            self.tokens[token] = current + self.ttl
            heapq.heappush(self.timeline, (current + self.ttl, token))

    def countUnexpiredTokens(self, current: int) -> int:
        self._remove(current)
        return len(self.tokens)

    def _remove(self, current):
        """移除过期验证码"""
        while self.timeline and self.timeline[0][0] <= current:
            time, token = heapq.heappop(self.timeline)
            if token in self.tokens and self.tokens[token] == time:
                self.tokens.pop(token)


if __name__ == "__main__":
    obj = AuthenticationManager(5)
    obj.generate("aaa", 1)
    obj.renew("aaa", 2)
    print(obj.countUnexpiredTokens(6))  # 1
    obj.generate("bbb", 7)
    obj.renew("aaa", 8)
    obj.renew("bbb", 10)
    print(obj.countUnexpiredTokens(15))  # 0
